package com.amtf.datafile2.core.std;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amtf.datafile2.DataField;
import com.amtf.datafile2.DataFieldDefinition;

public abstract class StdDataField<T extends DataFieldDefinition> implements DataField {
	protected T definition = null;
	protected String value = null;
	protected Map<String, Object> attributeMap = null;
	// protected Formula formula = null;
	protected List<String> errors = null;

	public StdDataField(T def) {
		this.definition = def;
		this.value = def.getDefaultValue();
	}

	public Object getAttribute(String name) {
		if (attributeMap == null) {
			return null;
		}

		return attributeMap.get(name);
	}

	public void setAttribute(String name, Object data) {
		if (attributeMap == null) {
			attributeMap = new HashMap<String, Object>();
		}

		this.attributeMap.put(name, data);
	}

	// public Formula getFormula() {
	// return formula;
	// }
	//
	// public void setFormula(Formula formula) {
	// this.formula = formula;
	// }

	public boolean isInvalid() {
		return errors != null && errors.size() != 0;
	}

	public List<String> getErrors() {
		return errors;
	}

	public void appendError(String message) {
		if (errors == null) {
			errors = new ArrayList<String>();
		}

		errors.add(message);
	}

	public void clearErrors() {
		errors = null;
	}

	public void setValue(String o) {
		this.value = o;
	}

	public String getValue() {
		return value;
	}

	public String getName() {
		return definition.getName();
	}

	public T getDefinition() {
		return definition;
	}

	// public void validate() {
	// try {
	// definition.validate(this);
	// } catch (DataException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// this.appendError(e.getMessage());
	// }
	// }

	public boolean equals(DataField obj) {
		if (obj.getValue() != null && this.value != null) {
			return obj.getValue().equals(this.value);
		} else if (obj.getValue() == null && this.value == null) {
			return true;
		}

		return false;
	}

	@Override
	public String toString() {
		// if (value!=null) {
		return value.toString();
		// }else {
		// return "":
		// }
	}
}
